import { observer, inject } from 'mobx-react'
import React, { useState, useMemo, useRef } from 'react'
import useSubs from '../../hooks/useSubs'

import video from '../../store/video'
import SvgIcon from '../common/svg-icon'
import VideoPlayer from '../common/video-player'
import common from '../../store/common'

const PlayBtn = () => {
  const { curScreenId } = video
  const { event$ } = common

  const [icon, setIcon] = useState('#iconplay')

  const VideoPlayerRef = useRef()

  useSubs(({ action, val }) => {
    if (action === 'videoStatus' && (val === 'stop' || val === 'play')) {
      setIcon('#iconplay')
    } else if (action === 'videoStatus' && val === 'pause') {
      setIcon('#iconpause')
    }
  })

  useMemo(() => {
    if (curScreenId) {
      const res = getStatus()
      setIcon(`#icon${res}`)
    }
  }, [curScreenId])

  function handleClick() {
    const { playVideo, pauseVideo } = VideoPlayerRef.current
    const res = getStatus()
    if (res !== 'pause') {
      // playVideo('hls', '//sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8')
      playVideo(
        curScreenId,
        'http://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-360p.mp4'
      )
      video.setStatus(curScreenId, 'pause')
      setIcon('#iconpause')
    } else {
      pauseVideo()
      video.setStatus(curScreenId, 'play')
      setIcon('#iconplay')
    }
    event$.emit({ action: 'playVideo', val: curScreenId })
  }

  function getStatus() {
    const screen = video.findScreenById(curScreenId)
    if (screen) {
      if (screen.status === 'pause') {
        return 'pause'
      }
    }
    return 'play'
  }

  return (
    <>
      <SvgIcon icon={icon} handleClick={handleClick} />
      <VideoPlayer ref={VideoPlayerRef} />
    </>
  )
}

export default inject('store')(observer(PlayBtn))
